package com.ruoyi.gift.service.impl;


import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.gift.domain.MaintenanceRecord;
import com.ruoyi.gift.domain.RoadSign;
import com.ruoyi.gift.domain.dto.RoadSignQuery;
import com.ruoyi.gift.domain.page.PageResult;
import com.ruoyi.gift.domain.vo.MaintenanceRecordVO;
import com.ruoyi.gift.domain.vo.RoadSignDetailVO;
import com.ruoyi.gift.domain.vo.RoadSignVO;
import com.ruoyi.gift.mapper.MaintenanceRecordMapper;
import com.ruoyi.gift.mapper.RoadSignMapper;
import com.ruoyi.gift.service.RoadSignService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class RoadSignServiceImpl implements RoadSignService {

    private final RoadSignMapper roadSignMapper;
    private final MaintenanceRecordMapper maintenanceRecordMapper;

    @Override
    public List<RoadSign> test(RoadSignQuery query){
        return roadSignMapper.test(query);
    }
    @Override
    @Transactional
    public int addRoadSign(RoadSign roadSign) {
        // 检查路牌编号是否唯一
        if (!isSignCodeUnique(roadSign.getSignCode(), null)) {
            throw new RuntimeException("路牌编号已存在：" + roadSign.getSignCode());
        }

        String username = SecurityUtils.getUsername();
        roadSign.setCreator(username).setUpdater(username);

        // 设置默认状态
        if (roadSign.getStatus() == null) {
            roadSign.setStatus(RoadSign.STATUS_NORMAL);
        }

        int result = roadSignMapper.insert(roadSign);
        if (result <= 0) {
            throw new RuntimeException("新增路牌失败");
        }
        log.info("新增路牌成功，编号：{}", roadSign.getSignCode());
        return result;
    }

    @Override
    @Transactional
    public int updateRoadSign(RoadSign roadSign) {
        RoadSign existing = roadSignMapper.selectById(roadSign.getId());
        if (existing == null) {
            throw new RuntimeException("路牌不存在");
        }

        // 检查路牌编号是否唯一（排除当前记录）
        if (!isSignCodeUnique(roadSign.getSignCode(), roadSign.getId())) {
            throw new RuntimeException("路牌编号已存在：" + roadSign.getSignCode());
        }

        String username = SecurityUtils.getUsername();
        roadSign.setUpdater(username)
                .setRemark(roadSign.getRemark());

        int result = roadSignMapper.update(roadSign);
        if (result <= 0) {
            throw new RuntimeException("更新路牌失败");
        }
        log.info("更新路牌成功，ID：{}", roadSign.getId());
        return result;
    }

    @Override
    public RoadSign getById(Long id) {
        return roadSignMapper.selectById(id);
    }

    @Override
    public RoadSign getBySignCode(String signCode) {
        return roadSignMapper.selectBySignCode(signCode);
    }

    @Override
    public PageResult<RoadSign> getRoadSignList(RoadSignQuery query) {
        Integer total = roadSignMapper.count(query);
        List<RoadSign> records = roadSignMapper.selectList(query);
        return new PageResult<>(records, total, query.getPageNum(), query.getPageSize());
    }

    @Override
    @Transactional
    public void deleteRoadSign(Long id) {
        RoadSign existing = roadSignMapper.selectById(id);
        if (existing == null) {
            throw new RuntimeException("路牌不存在");
        }

        // 检查是否存在维修记录
        int maintenanceCount = maintenanceRecordMapper.countBySignId(id);
        if (maintenanceCount > 0) {
            throw new RuntimeException("该路牌存在维修记录，无法删除");
        }

        int result = roadSignMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除路牌失败");
        }
        log.info("删除路牌成功，ID：{}", id);
    }

    @Override
    public RoadSignDetailVO getRoadSignDetail(Long id) {
        RoadSign roadSign = roadSignMapper.selectById(id);
        if (roadSign == null) {
            throw new RuntimeException("路牌不存在");
        }

        List<MaintenanceRecord> maintenanceRecords = maintenanceRecordMapper.selectBySignId(id);

        RoadSignDetailVO detailVO = new RoadSignDetailVO();

        // 设置路牌信息
        RoadSignVO roadSignVO = new RoadSignVO();
        BeanUtils.copyProperties(roadSign, roadSignVO);
        detailVO.setRoadSign(roadSignVO);

        // 设置维修记录
        List<MaintenanceRecordVO> recordVOs = maintenanceRecords.stream().map(record -> {
            MaintenanceRecordVO vo = new MaintenanceRecordVO();
            BeanUtils.copyProperties(record, vo);
            return vo;
        }).collect(Collectors.toList());
        detailVO.setMaintenanceRecords(recordVOs);

        // 设置统计信息
        detailVO.setTotalMaintenanceCount(recordVOs.size());
        double totalCost = recordVOs.stream()
                .mapToDouble(record -> record.getTotalFee() != null ? record.getTotalFee() : 0.0)
                .sum();
        detailVO.setTotalMaintenanceCost(totalCost);

        return detailVO;
    }

    @Override
    public boolean isSignCodeUnique(String signCode, Long excludeId) {
        int count = roadSignMapper.checkSignCodeExists(signCode, excludeId);
        return count == 0;
    }
}